package com.baomidou.springwind.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.framework.controller.SuperController;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.annotation.Permission;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springwind.common.HoorayosHelper;
import com.baomidou.springwind.common.SHA1Helper;
import com.baomidou.springwind.entity.App;
import com.baomidou.springwind.entity.Member;
import com.baomidou.springwind.entity.Permission1;
import com.baomidou.springwind.service.IMemberService;
import com.baomidou.springwind.service.IPermission1Service;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Koumiba
 * @since 2017-03-24
 */
@Controller
@RequestMapping("/sysapp/member")
public class MemberController extends SuperController {
	@Autowired
	private IMemberService memberService;
	@Autowired
	private IPermission1Service permissonService;
	/**
	 * 主页
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/index")
	public String index(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		//验证是否管理员
		int mid = HoorayosHelper.getMemberId(request);
		Member user = memberService.selectById(mid);
		if(!HoorayosHelper.checkAdmin(user)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noAdmin"));
			return "error";
		}
		// 验证权限
		int userPermissionId = user.getPermissionId().intValue(); 
		String appsId = permissonService.selectById(userPermissionId).getAppsId();
		if(!HoorayosHelper.checheckPermissions(appsId, "5")){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noPermissions"));
			return "error";
		}
		
		return "/sysapp/member/index";
	}
	
	/**
	 * 详情
	 */
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/detail")
	public String detail(Model model) {
		model.addAttribute("errorCode", HoorayosHelper.getErrorCodeMap());
		//验证是否登入
		if(!HoorayosHelper.checkLogin(request)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noLogin"));
			return "error";
		}
		//验证是否管理员
		int mid = HoorayosHelper.getMemberId(request);
		Member user = memberService.selectById(mid);
		if(!HoorayosHelper.checkAdmin(user)){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noAdmin"));
			return "error";
		}
		// 验证权限
		int userPermissionId = user.getPermissionId().intValue(); 
		String appsId = permissonService.selectById(userPermissionId).getAppsId();
		if(!HoorayosHelper.checheckPermissions(appsId, "5")){
			model.addAttribute("code", HoorayosHelper.getErrorCode("noPermissions"));
			return "error";
		}
		
		String memberId = request.getParameter("memberid");
		if(memberId!=null && !memberId.equals("")){
			Member member = memberService.selectById(memberId);
			model.addAttribute("member", member);
					
		}
		
		List<Permission1> permissionList = new Permission1().selectAll();
		model.addAttribute("permissionList", permissionList);		
		model.addAttribute("memberid", memberId);
		return "/sysapp/member/detail";
	}
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/ajax")
	public String ajax(String ac) {
		String display = "";
		if (ac.equals("getList")){
			String search_1 = request.getParameter("search_1");
			String search_2 = request.getParameter("search_2");
			int from = Integer.parseInt(request.getParameter("from"));
			int to = Integer.parseInt(request.getParameter("to"));
			EntityWrapper ew = new EntityWrapper<Member>();
			
			if(search_1!=null && !search_1.equals("")){
				ew.like("username", search_1);
			}
			if(search_2!=null && !search_2.equals("")){
				ew.where("type='"+search_2+"'");
			}
			
			List<Member> memberList = new Member().selectList(ew);
			display += memberList.size() + "<{|*|}>";
			for(int i=from; i<=to && i<memberList.size(); i++){
				Member v = memberList.get(i);
				display +="<tr class='list-bd'>";
					display +="<td style='text-align:left;padding-left:15px'><img src='getAvatar("+v.getTbid()+")' alt='"+v.getUsername()+"' class='membericon'><span class='membername'>"+v.getUsername()+"</span></td>";
					display +="<td>"+(v.getType() == 1 ? "管理员" : "普通会员")+"</td>";
					display +="<td><a href='javascript:openDetailIframe(\"detail.html?memberid="+v.getTbid()+"\");' class='btn btn-link'>编辑</a><a href='javascript:;' class='btn btn-link do-del' memberid='"+v.getTbid()+"'>删除</a></td>";
				display +="</tr>";
			}		
		}else if (ac.equals("del")){
			int tbid = Integer.parseInt(request.getParameter("memberid"));
			memberService.deleteById(tbid);
		}
		return display;
	}
	/**
	 * ajax页面
	 */
	@ResponseBody
	@Login(action = Action.Skip)
	@Permission(action = Action.Skip)
	@RequestMapping("/detailAjax")
	public String detailAjax(String ac) {
		
		if (ac.equals("edit")){
			String id = request.getParameter("id");
			String valUsername = request.getParameter("val_username");
			String valPassword = request.getParameter("val_password");
			String valType = request.getParameter("val_type");
			
			Member data = new Member();
			if(id==null || id.equals("")){
				data.setUsername(valUsername);
				valPassword = valPassword.equals("") ? valPassword : SHA1Helper.SHA1(valPassword);
				data.setPassword(valPassword);
				data.setType(Integer.parseInt(valType));
				if(valType.equals("1")){
					data.setPermissionId(Long.parseLong(request.getParameter("val_permission_id")));
				}
				
				EntityWrapper ew = new EntityWrapper<Member>();
				ew.orderBy("tbid", false);
				Member m = new Member().selectOne(ew);
				int nextId = m.getTbid().intValue()+1;
				data.setTbid((long)nextId);
				memberService.insert(data);
			}else{
				data = memberService.selectById(id);
				data.setType(Integer.parseInt(valType));
				if(valPassword!=null || !valPassword.equals("")){
					data.setPassword( SHA1Helper.SHA1(valPassword));
				}
				if(valType.equals("1")){
					data.setPermissionId(Long.parseLong(request.getParameter("val_permission_id")));
				}
				memberService.insertOrUpdate(data);
			}	
						
			Map<String,String> result = new HashMap<String,String>();
			result.put("info", "");
			result.put("status", "y");
			return JSONUtils.toJSONString(result);
		}else if(ac.equals("checkUsername")){
			String param = request.getParameter("param");
			EntityWrapper ew = new EntityWrapper<Member>();
			ew.where("username='"+param+"'");
			Map<String,String> result = new HashMap<String,String>();
			
			if(new Member().selectCount(ew) > 0){
				result.put("info", "用户名已存在，请更换");
				result.put("status", "n");
			}else{
				result.put("info", "");
				result.put("status", "y");
			}
			
			return JSONUtils.toJSONString(result);
		}
		return "";
	}
}
